package com.durablemethods.tsmserver.home;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.durablemethods.tsmserver.model.Position;
import com.durablemethods.tsmserver.model.TeamSummary;
import com.durablemethods.tsmserver.model.TraderPositionSummary;

public class TraderPositionSummaryHome {
	private PositionHome positionHome = new PositionHome();
	private SummaryHome summaryHome = new SummaryHome();
	
	public List<TraderPositionSummary> getPositionSummaries(){
		Map<String, TraderPositionSummary> positionSummariesByName = new HashMap<String, TraderPositionSummary>();
		Map<String, TeamSummary> teamsByMap = summaryHome.getTeamsByMap();
		List<Position> positions = positionHome.getPositions();
		for (Position position : positions) {
			String trader = position.getTrader();
			if (positionSummariesByName.containsKey(trader)){
				TraderPositionSummary traderPositionSummary = positionSummariesByName.get(trader);
				String team = position.getTeam();
				TeamSummary teamSummary = teamsByMap.get(team);
				Double payout = teamSummary.getPayout() * position.getShares();
				traderPositionSummary.getSharesByTeamMap().put(team, payout);
			}else{
				TraderPositionSummary newSummary = new TraderPositionSummary();
				newSummary.setTrader(trader);
				String team = position.getTeam();
				TeamSummary teamSummary = teamsByMap.get(team);
				Double payout = teamSummary.getPayout() * position.getShares();
				newSummary.getSharesByTeamMap().put(team, payout);
				positionSummariesByName.put(trader, newSummary);
			}
		}
		List<TraderPositionSummary> returnList = new ArrayList<TraderPositionSummary>();
		returnList.addAll(positionSummariesByName.values());
		Collections.sort(returnList, new TraderPositionSummaryComparator());
		return returnList;
		
	}
	
	class TraderPositionSummaryComparator implements Comparator<TraderPositionSummary>{

		@Override
		public int compare(TraderPositionSummary arg0,TraderPositionSummary arg1) {
			return arg0.getTrader().compareTo(arg1.getTrader());
		}
		
	}
}
